package com.arcsoft.crud.limitTime.base;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.arcsoft.crud.Constants.Global;
import com.google.common.util.concurrent.RateLimiter;

public abstract class BenchmarkTimeBase {
	
	private int warmTime;
	
	protected RateLimiter rateLimiter;
	
	protected int threadCount;
	
	protected CountDownLatch finishlatch;
	
	public BenchmarkTimeBase (int warmTime, int threadCount){
		this.warmTime = warmTime;
		this.threadCount = threadCount;
		this.rateLimiter = RateLimiter.create(threadCount/warmTime);
		finishlatch = new CountDownLatch(threadCount);
	}
	
	public void run() {
		
		System.out.printf(this.getClass().getSimpleName()+" start "+Global.THREAD_COUNT+" threads "+Global.WARMTIME+" s warmTime "+Global.EXECUTE_TIME+ " executeTime");
		ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
		for (int i = 0; i < threadCount; i++) {
			rateLimiter.acquire();
			threadPool.execute(getTask(i));
		}
		try {
			finishlatch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			threadPool.shutdownNow();
		}
		System.out.print("test all is finish");
	}    

	abstract protected Runnable getTask(int threadIndex);
}
